from django.shortcuts import render
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from book.models import Book, Author

users_info = {
    1: {'id': 1, 'name': '坤坤', 'age': 18, 'gender': '男', 'love': '打篮球'},
    2: {'id': 2, 'name': '张三', 'age': 18, 'gender': '女', 'love': '打网球'},
    3: {'id': 3, 'name': '李四', 'age': 18, 'gender': '女', 'love': '打羽毛球'},
}

users_data = [{'id': 1, 'name': '坤坤', 'text': '好好学习'},
              {'id': 2, 'name': '张三', 'text': '天天向上'},
              {'id': 3, 'name': '李四', 'text': '3333333'},
              {'id': 4, 'name': '王五', 'text': '44444444'},
              {'id': 5, 'name': '赵六', 'text': '5555555555'},
              {'id': 6, 'name': '晓东', 'text': '88888888'}]


def personage(request, key):
    """显示个人信息数据"""
    userinfo = users_info[int(key)]
    return render(request, 'personage.html', {'userinfo': userinfo})


def user_info(request):
    """显示所有的博客"""

    # 对书的价格进行聚合查询
    # from book.models import Book
    # from django.db.models import Max, Avg, Sum
    # ret = Book.objects.aggregate(max_price=Max('price'), avg_price=Avg('price'), sum_price=Sum('price'))
    # print(ret)
    # print(ret['max_price'])       # 书本的最大价格
    # print(ret['avg_price'])       # 书本的平均值
    # print(ret['sum_price'])       # 书本的总价格

    # F 对象查询练习
    # from django.db.models import F
    # from book.models import Book
    # # 对所有书涨价20元
    # Book.objects.all().update(price=F('price') + 20)

    # 多对多表的数据关联
    # from book.models import Course, Student
    # student = Student.objects.get(id=1)
    # student.course.add(Course.objects.get(id=1))

    # 添加一对一扩展表的数据关联
    # from book.models import ExtendInfo, Person
    # person = Person.objects.get(id=1)
    # ExtendInfo(person=person, love='篮球', marriage=True, bloodType='O').save()

    """
    Tom, 20, M, Beijing
    Jerry, 22, M, Shanghai
    Lucy, 21, F, HangZhou
    Lily, 19, F, Chengdu
    """
    # data = [['Tom', 20, 'M', 'Beijing'],
    #         ['Jerry', 22, 'M', 'Shanghai'],
    #         ['Lucy', 21, 'F', 'HangZhou'],
    #         ['Lily', 19, 'F', 'Chengdu]']]
    #
    # from book.models import Person
    # for name, age, gender, city in data:
    #     Person(name=name, age=age, gender=gender, city=city).save()

    '''
    小练习：
    查询 Person 表格中 age 大于等于 20 岁且 city 不为 Beijing 的人员信息，输出结果
    查询 Person 表格中 city 为 Shanghai 的人员信息， 按照 age 升序排序。
    统计 Person 表格中每个 city 出现的次数，按照出现数量降序排序。
    查询 Person 表格中 age 最大的人员信息。
    '''
    # from django.db.models import Q
    # 查询 Person 表格中 age 大于等于 20 岁且 city 不为 Beijing 的人员信息，输出结果
    # 方法一：
    # print(Person.objects.filter(Q(age__gte=20) & ~Q(city='Beijing')))
    # 方法二：
    # print(Person.objects.filter(age__gte=20).exclude(city='Beijing'))

    # 查询 Person 表格中 city 为 Shanghai 的人员信息， 按照 age 升序排序。
    # print(Person.objects.filter(city='Shanghai').order_by('age'))

    # 统计 Person 表格中每个 city 出现的次数，按照出现数量降序排序。
    # from django.db.models import Count
    # print(Person.objects.values('city').annotate(count=Count('city')).order_by('-count'))

    # 查询 Person 表格中 age 最大的人员信息
    # print(Person.objects.all().order_by('-age').__iter__().__next__())
    # for i in (Person.objects.all().order_by('-age')):
    #     print(f'年龄最大值为:{i.age}')
    #     break

    # 数据增加
    # from book.models import Book, Author
    # 增加作者
    # Author(name='喜洋洋', age=22, email='123@444qq.com', gender='male').save()

    # 增加书籍
    # Book(title='西红柿炒蛋的10000做法', price='9999999', Author=Author.objects.get(id=3)).save()

    # 修改数据 get 获取一个数据
    # book = Book.objects.get(id=4)
    # book.price = 10000
    # book.save()

    # 数据删除
    # book = Book.objects.get(id=3)
    # book.delete()

    # 数据库的查询
    # 获取所有的数据
    # books = Book.objects.all()
    # # QuerySet 查询集   排序
    # print(books)
    # for i in books:
    #     print(i.title, i.price, i.Author.name)   # Author object(1)

    # 筛选 __方法   lt '小于' gt '大于' lte '小于等于' gte '大于等于'
    # books = Book.objects.filter(title__gt=10000)
    # print(books)
    # for i in books:
    #     print(i.title, i.price, i.Author.name)

    # 过滤，排除  将数据里大于10000的数据去除掉
    # books = Book.objects.exclude(title__gt=10000)

    # 或者 和 与
    # from django.db.models import Q
    # 或者
    # books = Book.objects.filter(Q(price__gt=10000) | Q(id=5))
    # 与
    # books = Book.objects.filter(Q(price__gt=10000), Q(id=5))
    # print(books)
    # for i in books:
    #     print(i.title, i.price, i.Author.name)

    # 去重查询
    # books1 = Book.objects.values('title').distinct()
    # print(books1)
    #
    # books2 = Book.objects.values_list('title').distinct()
    # print(books2)

    # from django.db.models import Count
    #
    # # 分组聚合  将相同名字的数据分为一组
    # books = Book.objects.values('title').annotate(count=Count('title'))
    # print(books)

    # 排序 默认升序 降序在字段前加负号
    # books = Book.objects.all().order_by('price')
    # # 降序
    # # books = Book.objects.all().order_by('-price')
    # for i in books:
    #     print(i.title, i.price, i.Author.name)

    # 分页操作
    # from django.core.paginator import Paginator
    # books = Book.objects.all()
    # paginator = Paginator(books, 3)
    # for i in paginator.get_page(1):
    #     print(i)
    # paginator.get_page(2)

    # 模糊查询
    # books = Book.objects.filter(title__icontains='python')
    # print(books)

    return render(request, 'user_info.html', {'user_data': users_data})


# 设置cookie


def set_cookie_view(request):
    resp = HttpResponse()
    resp.set_cookie('username', 'admin', 10000)
    return resp


def get_cookie_view(request):
    result = request.COOKIES.get('username')
    return HttpResponse(result)


# 1 判断用户是否有cookie session 是否还可以使用 直接进入页面
# 2 显示登录页面 登陆完成后记录cookie
# 3 退出登陆 清除所有的cookie 和 session


# 主页面视图
def user(request):
    # 如果登陆成功， 就返回账号，书的所有信息
    if request.COOKIES.get('username'):
        if request.COOKIES.get('username'):
            from book.models import Book
            data = {'username': request.COOKIES.get('username'),
                    'books': Book.objects.all()}
            return render(request, 'user/user.html', data)
    # 如果cookie不存在，跳转到登录页面
    return HttpResponseRedirect('/blog/login')


def add_books(request):
    """添加书籍"""
    book_title = request.POST.get('book_title', '')
    book_price = request.POST.get('book_price', '')
    book_author = request.POST.get('book_author', '')

    info = {'title': book_title,
            'price': book_price,
            'author': book_author}

    # 判断数据是否为空
    print([book_author, book_price, book_title])
    if book_title == '' or book_price == '' or book_author == '':
        info['info'] = '请填写完整数据'
        return render(request, 'user/add_book.html', info)

    # 判断作者是否存在
    from book.models import Author, Book
    books = Author.objects.filter(name=book_author)
    if not books:
        info['info'] = '作者不存在'
        return render(request, 'user/add_book.html', info)
    # 查询数据是否重复
    books = Book.objects.filter(title=book_title, Author__name=book_author)
    if books:
        info['info'] = '书籍信息重复'
        return render(request, 'user/add_book.html', info)
    # 添加书信息
    Book(title=book_title, price=book_price, Author=Author.objects.get(name=book_author)).save()
    return HttpResponseRedirect('/blog/user')


def search_books(request):
    """查询页面"""
    search_name = request.GET.get('search_name', '')
    # 数据库中查找对应的书籍
    books = Book.objects.filter(title=search_name)
    data = {'books': books, 'book_name': search_name}
    return render(request, 'user/search_books.html', data)


def login(request):
    """登录"""
    print('method', request.method)
    if request.method == 'GET':
        # 请求页面 有没有cookie
        if 'username' in request.COOKIES:
            if request.COOKIES.get('username'):
                print('request.COOKIES.get(username)', request.COOKIES.get('username'))
                # 返回到首页的数据
                return HttpResponseRedirect('/blog/user')

        # 第一次使用
        data = {
            'username': '',
            'password': '',
            'error': '',
        }
        return render(request, 'login/login.html', data)

    if request.method == 'POST':
        # 获取用户输入的账号密码
        username = request.POST.get('username')
        password = request.POST.get('password')
        # 从数据库里判断对比账号密码
        from blog.models import User
        # 判断密码是否有问题
        result = User.objects.filter(username=username, password=password)
        if result:
            # 账号密码正确记录登录信息

            # 重定向到用户页面，携带username数据
            response = HttpResponseRedirect('/blog/user')
            # 设置cookie
            response.set_cookie('username', username, 60 * 60)
            return response
        else:
            # 当账号密码不正确的时候
            data = {
                'username': username,
                'password': password,
                'error': '你的账号或密码错误',
            }
            return render(request, 'login/login.html', data)


def logout(request):
    """注销登录"""
    from django.http import HttpResponseRedirect
    res = HttpResponseRedirect('/blog/login')  # 重新跳转到登录页面
    # 清除username信息
    if 'username' in request.session:
        del request.session['username']
    if 'username' in request.COOKIES:
        res.delete_cookie('username')
    return res


def update(request, book_id):
    """更新书信息"""
    if request.method == 'GET':
        print('book_id', book_id, request.method)
        book = Book.objects.get(id=book_id)
        if book:
            return render(request, 'user/update.html', {'book': book})

    elif request.method == 'POST':
        # 获取数据
        book = Book.objects.get(id=book_id)
        title = request.POST.get('title')
        price = request.POST.get('price')
        name = request.POST.get('name')

        # 让修改数据时出现错误，数据仍然保留
        args = {'id': book_id, 'title': title, 'price': price, 'Author': {'name': name}}

        # 检测价格是否超出范围
        if len(str(int(float(price)))) > 10:
            info = {'error': '金额数值超出范围', 'book': args}
            return render(request, 'user/update.html', info)

        # 检查作者参数
        if not Author.objects.filter(name=name):
            # get 数据对象 book object
            # filter 数据集合 <QuerySet> {<book object>, <book object> }
            info = {'error': '没有找到该作者名称', 'book': args}
            return render(request, 'user/update.html', info)

        # 修改数据
        book.title = title
        book.price = float(price)
        book.Author_id = Author.objects.get(name=name)
        book.save()

        return HttpResponseRedirect('/blog/user')


def remove(request, book_id):
    """删除书的信息"""
    book = Book.objects.get(id=book_id)
    book.delete()
    return HttpResponseRedirect('/blog/user')
